---
title: Miscellaneous
hide_table_of_contents: true
description: Assorted utilities and other exports
---

import { DemoLink } from '@site/src/components/DemoLink';
import Details from '@theme/Details';

%importmd ../\_ts_admonition.md

A partial list of exports from `react-querybuilder`.

## Utilities

### `transformQuery`

```ts
function transformQuery(query: RuleGroupTypeAny, options: QueryTransformerOptions): any;
```

This function recursively processes a query object (`RuleGroupType` or `RuleGroupTypeIC`), passing each `RuleType` object to a provided `ruleProcessor` function. Available options include:

- `ruleProcessor`: Custom processing function for each rule.
- `ruleGroupProcessor`: Custom processing function for each rule group. Each group's `rules` property is retained and recursively processed regardless of other mutations.
- `propertyMap`: Keys in rule or group objects that match keys in this object are renamed to the corresponding value.
- `combinatorMap`: Translates combinators; for example, `{and: "&&", or: "||"}` would convert "and"/"or" combinators to "&&"/"||", respectively.
- `operatorMap`: Converts operators that match keys in this object to corresponding values, e.g., `{"=": "=="}`.
- `deleteRemappedProperties`: Defaults to `true`; pass `false` to retain both remapped properties _and_ original properties in the resulting object.

See the [test suite](https://github.com/react-querybuilder/react-querybuilder/blob/main/packages/react-querybuilder/src/utils/transformQuery.test.ts) for example usage.

### `defaultValidator`

```ts
function defaultValidator(query: RuleGroupTypeAny): {
  [id: string]: { valid: boolean; reasons?: string[] };
};
```

Pass `validator={defaultValidator}` to automatically validate groups (rules are ignored). A group is marked invalid when either of these conditions are true:

1. The group has no child rules or groups (`query.rules.length === 0`)
2. The group has a missing/invalid `combinator` property and more than one child rule or group (`rules.length >= 2`)

You can see the default validator in action in the [demo](/demo) by checking the <DemoLink option="validateQuery" text="'Use validation' option" />. Empty groups display bold text on their "+ Rule" button and a description where rules normally appear.

### `findPath`

```ts
function findPath(path: Path, query: RuleGroupTypeAny): RuleType | RuleGroupTypeAny | null;
```

`findPath` finds the rule or group within the query hierarchy that has a given `path`. This is useful in custom [`onAddRule`](../components/querybuilder#onaddrule) and [`onAddGroup`](../components/querybuilder#onaddgroup) functions.

More extensive documentation on the `path` property is [here](../tips/path).

### `findID`

```ts
function findID(id: string, query: RuleGroupTypeAny): RuleType | RuleGroupTypeAny | null;
```

`findID` finds the rule or group within the query hierarchy that has a given `id`.

### `convertQuery`

```ts
function convertQuery(query: RuleGroupType): RuleGroupTypeIC;
// OR
function convertQuery(query: RuleGroupTypeIC): RuleGroupType;
```

`convertQuery` toggles a query between the conventional `RuleGroupType` structure (with combinators at the group level) and the "independent combinators" structure `RuleGroupTypeIC` (with combinators between every other rule/group).

`convertToIC` and `convertFromIC` perform the same function as `convertQuery` but only in the directions indicated by their names.

## Query tools

Several methods are available to assist with programmatic manipulation of query objects. These methods are used by the `<QueryBuilder />` component itself, so they're guaranteed to achieve the same result as a corresponding UI-based update. Each method returns the modified query.

Check out the ["External controls" Tips & Tricks page](../tips/external-controls) to see these methods used outside the `<QueryBuilder />` component context.

### `add`

`(query: RuleGroupTypeAny, ruleOrGroup: RuleGroupTypeAny | RuleType, parentPathOrID: Path | string, options: AddOptions) => RuleGroupTypeAny`

Adds a rule or group (and an independent combinator if necessary to keep the query valid) to the group at the specified `path` or with the given `id`.

<Details summary="AddOptions">

%importcode /packages/core/src/utils/queryTools.ts#blockName=AddOptions

</Details>

### `remove`

`(query: RuleGroupTypeAny, pathOrID: Path | string) => RuleGroupTypeAny`

Removes a rule or group (and the preceding independent combinator if one exists) at the specified `path` or with the given `id`.

### `update`

`(query: RuleGroupTypeAny, prop: string, value: any, pathOrID: Path | string, options: UpdateOptions) => RuleGroupTypeAny`

Updates a property of a rule or group, or an independent combinator, at the specified `path` or with the given `id`.

<Details summary="UpdateOptions">

%importcode /packages/core/src/utils/queryTools.ts#blockName=UpdateOptions

</Details>

### `move`

`(query: RuleGroupTypeAny, oldPathOrID: Path | string, newPath: Path | 'up' | 'down', options: MoveOptions) => RuleGroupTypeAny`

Moves (or clones with a new `id`) a rule or group at the specified `path` or with the given `id` to a new location in the query tree. Using `"up"` or `"down"` as the `newPath` will "shift" the rule or group higher or lower, respectively.

<Details summary="MoveOptions">

%importcode /packages/core/src/utils/queryTools.ts#blockName=MoveOptions

</Details>

### `insert`

`(query: RuleGroupTypeAny, ruleOrGroup: RuleGroupTypeAny | RuleType, path: Path, options: InsertOptions) => RuleGroupTypeAny`

Inserts a rule or group (and an independent combinator if necessary to keep the query valid) at the specified `path`.

<Details summary="InsertOptions">

%importcode /packages/core/src/utils/queryTools.ts#blockName=InsertOptions

</Details>

### `group`

`(query: RuleGroupTypeAny, sourcePathOrID: Path | string, targetPathOrID: Path | string, options: GroupOptions) => RuleGroupTypeAny`

Creates a new group at the target `path` (based on the specified `path` or given `id`) containing the existing rule/group at that path and the rule/group at the source path (or with the source `id`), in that order, in its `rules` array.

<Details summary="GroupOptions">

%importcode /packages/core/src/utils/queryTools.ts#blockName=GroupOptions

</Details>

## Number parsing

HTML `<input>` controls store values as strings (even for `type="number"`), but your requirements may call for true numeric values. The [`parseNumbers`](../components/querybuilder#parsenumbers) prop on the `QueryBuilder` component and the `formatQuery` function's [`parseNumbers`](./export#parse-numbers) option can be used to convert values to numeric types from the UI or during export, respectively. Both configuration options have the same valid values (per the type below) and behave similarly.

`boolean | "enhanced" | "enhanced-limited" | "native" | "native-limited" | "strict" | "strict-limited"`

> _Tip: Try the **`"strict-limited"`** option first._

- The `"*-limited"` options are equivalent to their non-suffixed counterparts except that numeric parsing is only performed when the value editor's `inputType` is `"number"`.
  - Being based on the `inputType`, the `"*-limited"` suffix can only affect `formatQuery` output when a `fields` array is also provided.
- `true`, `"strict"`, and `"enhanced"` will retain the original value when numeric parsing fails.
- `"enhanced"` and `"native"` can lead to information loss since any trailing invalid characters will be removed.
- `true` and `"strict"` determine numericity using [`numeric-quantity`](https://www.npmjs.com/package/numeric-quantity) with `allowTrailingInvalid: false`. Values must be numeric _in their entirety_ to be considered numeric, not just _start_ with a number as with `parseFloat`.
- `"enhanced"` uses `numeric-quantity` with `allowTrailingInvalid: true`.
- `"native"` uses JavaScript's native `parseFloat` method, which is similar to the "enhanced" algorithm in that it will strip trailing invalid characters, but it will return `NaN` for non-numeric values instead of the original value.

#### Examples

```ts
const query: RuleGroupType = {
  combinator: 'and',
  not: false,
  rules: [
    { field: 'digits', operator: '=', value: '20' },
    { field: 'age', operator: 'between', value: '26, 52' },
    { field: 'lastName', operator: '=', value: 'Vai' },
  ],
};

// Default configuration - all values are strings:
formatQuery(query, { format: 'sql' });
// "(digits = '20' and age between '26' and '52' and lastName = 'Vai')"

// `parseNumbers: true` - numeric strings converted to actual numbers:
formatQuery(query, { format: 'sql', parseNumbers: true });
// "(digits = 20 and age between 26 and 52 and lastName = 'Vai')"
```

:::info More about the "strict" option

To avoid information loss, the `true` and `"strict*"` options are more strict about what qualifies as "numeric" than [the standard `parseFloat` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat). To oversimplify a bit, `parseFloat` works with any string that _starts_ with a numeric sequence, ignoring the rest of the string beginning with the first non-numeric character. In contrast, when `parseNumbers` is `true`, `formatQuery` will only convert a `value` to a `number` if it appears to be numeric _in its entirety_ (after trimming whitespace).

Each of the following expressions evaluates to `true`:

```ts
// Everything after the '3' is ignored by `parseFloat`
parseFloat('000123abcdef') === 123;

// `value` contains non-numeric characters, so remains as-is
formatQuery(
  { rules: [{ field: 'f', operator: '=', value: '000123abcdef' }] },
  { format: 'sql', parseNumbers: true }
) === "(f = '000123abcdef')";

// `value` is wholly numeric (after trimming whitespace) so it gets converted to a number
formatQuery(
  { rules: [{ field: 'f', operator: '=', value: '  000123  ' }] },
  { format: 'sql', parseNumbers: true }
) === '(f = 123)';
```

:::

## Defaults

The default configuration objects are exported for convenience, including the following.

- `defaultCombinators` (see [`combinators` prop](../components/querybuilder#combinators))
- `defaultOperators` (see [`operators` prop](../components/querybuilder#operators))
- `defaultTranslations` (see [`translations` prop](../components/querybuilder#translations))
- `defaultValueProcessor` and variants for non-SQL formats (see [Export](./export) > [Value processor](./export#value-processor))
- `defaultFields` (see [`fields` prop](../components/querybuilder#fields))
- `standardClassnames` (see [CSS classes](../styling/classnames))

The default components are also exported:

- [`ActionElement`](../components/actionelement) - used for action buttons (to add rules, remove groups, etc.)
- [`DragHandle`](../components/draghandle) - used for the drag handle on rules and group headers
- [`InlineCombinator`](../components/rulegroup) - used when either [`showCombinatorsBetweenRules`](../components/querybuilder#showcombinatorsbetweenrules) is `true` or the query is using independent combinators.
- [`NotToggle`](../components/nottoggle) - used for the "Invert this group" toggle switch
- [`Rule`](../components/rule) - the default rule component
- [`RuleGroup`](../components/rulegroup) - the default rule group component
- [`ShiftActions`](../components/shiftactions) - used for the "shift up"/"shift down" buttons when [`showShiftActions`](../components/querybuilder#showshiftactions) is `true`
- [`ValueEditor`](../components/valueeditor) - the default `valueEditor` component
- [`ValueSelector`](../components/valueselector) - used for drop-down lists (combinator, field, and operator selectors)
